module.exports = (ctx) => {
  const register = () => {
    ctx.helper.uploader.register('giteetang', {
      handle,
      name: 'Gitee图床',
      config: config
    })
  }
  const handle = async function (ctx) {
    let userConfig = ctx.getConfig('picBed.giteetang')
    if (!userConfig) {
      throw new Error('Can\'t find uploader config')
    }
    let now = new Date()
    let year = now.getFullYear()
    let month = now.getMonth()
    let day = now.getDay()
    let hours = now.getHours()
    let minutes = now.getMinutes()
    let seconds = now.getSeconds();

    const baseUrl = 'https://gitee.com'
    const repo = userConfig.repo
    const path = userConfig.path + "/" + year + "/" + month
    const token = userConfig.token
    const branch = userConfig.branch
    const realImgUrlPre = baseUrl + '/'+ repo + '/raw/master/' + path
    const realUrl = baseUrl + '/api/v5/repos/' + repo + '/contents/' + path

    try {
      let imgList = ctx.output
      for (let i in imgList) {
        let image = imgList[i].buffer
        if (!image && imgList[i].base64Image) {
          image = Buffer.from(imgList[i].base64Image, 'base64')
        }

        const message = "Upload "+imgList[i].fileName+" .by picgo - " + year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds 
        // const message = userConfig.repo + ":" + userConfig.dir + ":" + userConfig.branch
        let perRealUrl = realUrl + '/' + imgList[i].fileName
        const postConfig = postOptions(perRealUrl, token, image, message,branch)
        // post config log
        ctx.log.info(JSON.stringify(postConfig))
        let body = await ctx.Request.request(postConfig)
        delete imgList[i].base64Image
        delete imgList[i].buffer
        body = JSON.parse(body)
        imgList[i]['imgUrl'] = realImgUrlPre + '/' + imgList[i].fileName
      }
    } catch (err) {
      // ctx.log.info(JSON.stringify(err))
      ctx.emit('notification', {
        title: '上传失败',
        body: JSON.stringify(err)
      })
    }
  }

  const postOptions = (url, token, image, message,branch) => {
    let headers = {
      contentType: 'application/json;charset=UTF-8',
      'User-Agent': 'PicGo'
    }
    let formData = {
      'access_token': token,
      'content': image.toString('base64'),
      'message': message || '',
      'branch': branch || 'master'
    }
    const opts = {
      method: 'POST',
      url: url,
      headers: headers,
      formData: formData
    }
    return opts
  }

  const config = ctx => {
    let userConfig = ctx.getConfig('picBed.giteetang')
    if (!userConfig) {
      userConfig = {}
    }
    return [
      {
        name: 'repo',
        type: 'input',
        default: userConfig.repo,
        required: true,
        message: 'repo',
        alias: 'repo'
      },
      {
        name: 'branch',
        type: 'input',
        default: 'master',
        required: true,
        message: 'master',
        alias: 'branch'
      },
      {
        name: 'path',
        type: 'input',
        default: userConfig.path,
        required: false,
        message: 'path',
        alias: 'path'
      },
      {
        name: 'token',
        type: 'input',
        default: userConfig.token,
        required: true,
        message: '5664b5620fb11111e3183a98011113ca31',
        alias: 'token'
      }
    ]
  }
  return {
    uploader: 'giteetang',
    register
  }
}